// JavaScript Document

function goToEventPage(pageNum) {
    var start = (pageNum * 9) - 8;
    var end = start + 8;

    for (i = start; i < end; i++) {
        jq("ul.event-items > li").each(function (j) {
            var eventNum = jq(this).attr("data-item-num");

            if (eventNum >= start && eventNum <= end) {
                jq(this).show();
            } else {
                jq(this).hide();
            }

            //if(!jq(this).is(":nth-child(" + (j+1) + ")")){
            //    jq(this).hide();
            //}
        });
    }
}

jq(document).ready(function () {
    var url = window.location.href.toLowerCase();
    var eventsItem = jq(".event-items li");

    if (eventsItem.length <= 9) {
        jq(".pageNumbers").hide();
    }

    // Hides the eventsHolder section if the URL contains "?EventID="
    if (url.indexOf("?eventid=") > -1) {
        jq('.eventsHomeText').css('display', 'none');
        //add a class when in event details view
        jq('#main').addClass('eventDetailsPage');
    }

    if (jq('.event-content').length) {
        // Removes content above the events details section
        jq("figure.main-banner").remove();
        jq(".intro-info").remove();
        jq(".event-content").css({
            "padding-top": "0",
            "margin-top": "-30px"
        });

        //if (url.indexOf("?eventid") > -1){
        //    jq('#allEventsSections').prevAll().remove();
        //}

        //Email a friend link popup
        jq('body').on('click', '.event-sidebar .share', function () {
            jq('.emailPopUp').fadeIn('slow');
            jq('.emailTo').focus();
            //Setting the opacity for IE here prevents the bg colour turning solid
            jq('.eventBG').css('filter', 'alpha(opacity=70)');
            jq('.eventBG').fadeIn('slow');
        });


        //Cancel button on email a friend popup
        jq('.btnEmailCancel').click(function (e) {
            jq('.emailPopUp').fadeOut('slow');
            jq('.eventBG').fadeOut('slow');
            jq('.fromName').text("");
            jq('.emailField').val("");
            jq('#emailMsgName').text("");
            jq('.emailPopupErrors').css('display', 'none');
            jq('.emailErrorMsg').hide();
        });

        //Does the same as above, but when the escape key is pressed
        var popupVisible = jq('.emailPopUp').attr('style');
        if (jq(popupVisible == "display: block;")) {
            jq(document).keyup(function (objEvent) {
                if (objEvent.keyCode == 27) {
                    jq('.btnEmailCancel').click();
                    jq('.emailPopupErrors').css('display', 'none');
                }
            });
        };


        //"Your friend's name" on email a friend popup
        jq('.emailFriendName').blur(function () {
            jq('#emailMsgName').text(this.value);
        });

        //"Your name" on email a friend popup
        jq('.emailYourName').blur(function () {
            jq('.fromName').text(this.value);
        });

        //Checks if any of the field errors are visible and if so, display general error message next to buttons
        jq('.btnEmailSend').click(function () {
            var numErrors = jq('.emailPopupErrors:visible').length;
            if (numErrors > 0) {
                jq('.emailErrorMsg').css("display", "block");
            };
        });

        //Removes general error message if there are no other errors when an input field has lost focus
        jq('.emailField').blur(function () {
            var numErrors = jq('.emailPopupErrors:visible').length;
            if (numErrors == 0) {
                jq('.emailErrorMsg').css("display", "none");
            };
        });


        //jq(".tablesorter")
        // Disables sorting on events table columns 2 & 3
        // Orders columns in descending order on first sort
        //.tablesorter({ headers: { 2: { sorter: false }, 3: { sorter: false} }, sortInitialOrder: 'desc' })

        // Only displays x number of table rows at a time.
        // Ensure this matches the pagerOption values on lines 335 & 336 in ForthcomingEvents.ascx.vb
        // otherwise this will mess the table up when it's resorted
        //.tablesorterPager({ container: jq("#pager"), size: 100 });

        // Hides the page scroll buttons if there is only one page, as they're pointless
        var pages = jq('input.pagedisplay').val();
        //if (jq('input.pagedisplay').is(':visible')) {
        if (jq('input.pagedisplay').length) {
            jq('input.pagedisplay').attr("disabled", "disabled");
            if (pages.indexOf("/1") > -1) {
                jq('#pager').hide();
            };
        };



        // Changes the layout of the events table for smaller screens
        function changeEventsTable() {
            if (window.innerWidth < 680) {
                var pageDisplay = jq('#pageDisplay').val();
                var pageNum = pageDisplay.split("/");

                for (i = 0; i < pageNum[1]; i++) {
                    jq('table.tablesorter').first().clone().appendTo('.mobileEventsHolder').children().addClass("group" + (i + 1));
                    if ((i + 1) / pageNum[1] < 1) {
                        jq('span.next')[0].click();
                    } else {
                        jq('table.tablesorter').first().remove();
                        jq('.pager').remove();
                    }
                }

                jq('table.tablesorter').each(function (i) {
                    var $this = jq(this);

                    $this.children('thead').remove();
                    $this.children('.pager').remove();

                    $this.replaceWith(jq(this).html()
                        .replace(/<tbody/gi, "<div")
                        .replace(/<tr/gi, "<div class='eventBlock'")
                        .replace(/<td/gi, "<div")
                        .replace(/<\/td>/gi, "</div>")
                        .replace(/<\/tr>/gi, "</div>")
                        .replace(/<\/tbody/gi, "<\/div")
                    );

                    // Change value of $this, as table no longer exists at this point
                    $this = jq('.group' + (i + 1));

                    jq("<div class='eventLabels'>Date:</div>").insertAfter($this.find("div.tdDetails"));
                    jq("<div class='eventLabels'>Location:</div>").insertAfter($this.find("div.tdDate"));
                    jq("<div class='eventLabels'>Event Area:</div>").insertAfter($this.find("div.tdLocation"));
                    jq("<div class='eventLabels'>Event Type:</div>").insertAfter($this.find("div.tdArea"));

                    // Any blank Divs are filled with "Tbc" to prevent them from being populated with the next Div's content
                    jq('div.eventLabels').each(function () {
                        if (jq(this).next().text() == "") {
                            jq(this).next().text("Tbc");
                        };
                    });
                });
            };
        }

    } else {
        var pages = jq("ul.event-items > li").length;

        // Only displays the first 9 events on page load
        jq("ul.event-items > li").each(function (i) {
            if (i > 8) {
                jq(this).hide();
            }
        });
    }

    // Change events page
    jq("body").on("click", ".pageNumbers span", function () {
        goToEventPage(jq(this).text());

        setTimeout(function(){
            jq('html, body').animate({
                scrollTop: jq(".eventsCalendar").offset().top - 100
            }, 300);
        }, 300);
    });
});



jq(window).load(function () {
    // Text is displayed to the right of the event details images if
    // the total width of these images is < half the width of imagesDiv
    var totalImgWidth = 0
    jq('.imagesDiv img').each(function () {
        totalImgWidth += jq(this).width();
    });

    if (totalImgWidth < jq('.imagesDiv').width() / 2) {
        jq('.imagesDiv').css('float', 'left');
    };
});